<template>
  <div>
    <div>
      <span @click="toChina">全国</span>
      {{ (provinceName?'>':'') }}
      <span v-if="provinceName" @click="toProvince(provinceName)">{{ provinceName }}</span>
      {{ (provinceName && cityName?'>':'') }}
      <span v-if="provinceName && cityName">{{ cityName }}</span>
    </div>
    <div id="main" ref="chart" />
  </div>
</template>
<script>
import { registerMap } from 'echarts/core' // 引入注册地图的方法
import * as echarts from 'echarts'
// 基于准备好的dom，初始化echarts实例
import chinaJson from '@/data/china.json' // 引入地图数据
import Axios from 'axios'

const transformCode = (json) => {
  const mapCode = {}
  json.features.forEach(item => {
    mapCode[item.properties.name] = item.properties.adcode
  })
  return mapCode
}

registerMap('china', chinaJson) // 注册地图
export default {
  data() {
    return {
      chart: null,
      mapOption: {},
      option: {},
      provinceName: '',
      cityName: '',
      provinceCodeMap: {},
      cityCodeMap: {}
    }
  },
  watch: {
    option: {
      handler() {
        this.setChartOption(this.option)
      },
      deep: true
    }
  },
  mounted() {
    this.provinceCodeMap = transformCode(chinaJson)

    this.chart = echarts.init(this.$refs.chart)
    // this.mapChart = echarts.init(this.$refs.mapChart)
    this.option = {
      // geo 用来配置地图
      geo: {
        map: 'china', // map接的就是注册地图时候的名称
        emphasis: {
          label: {
            show: false
          },
          itemStyle: {
            areaColor: 'red'
          }
        },
        itemStyle: {
          areaColor: '#323c48',
          borderColor: '#111'
        }
      }
    }
    this.chart.on('click', (params) => {
      const { name } = params // 获取省份名称 -> 去找adcode -> 调接口获取地图数据 -> 注册地图 -> 更新图表数据
      if (!this.provinceName) {
        this.toProvince(name)
      } else {
        this.toCity(name)
      }
    })
  },
  methods: {
    toChina() {
      this.option.geo.map = 'china'
      this.provinceName = ''
      this.cityName = ''
    },
    toProvince(name) {
      const vm = this
      Axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${vm.provinceCodeMap[name]}_full.json`).then(res => {
        vm.cityCodeMap = transformCode(res.data)
        registerMap(name, res.data) // 注册地图
        vm.provinceName = name
        vm.cityName = ''
        vm.option.geo.map = name
      })
    },
    toCity(name) {
      const vm = this
      Axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${vm.cityCodeMap[name]}_full.json`).then(res => {
        registerMap(name, res.data)
        vm.cityName = name
        vm.option.geo.map = name
      })
    },
    setChartOption(option) {
      this.chart.setOption(option)
    }
  }
}
</script>

<style>
span{
    display: inline-block;
    padding: 10px;
    cursor: pointer;
}
#main{
    width: 50%;
    height: 60vh;
}
#mapChart{
      width: 50%;
    height: 60vh;
}
</style>
